package com.rujian.passwordmanager.ui;

import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.support.v7.app.AlertDialog;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.support.design.widget.NavigationView;
import android.support.v4.view.GravityCompat;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuItem;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.rujian.passwordmanager.R;
import com.rujian.passwordmanager.adapter.PwdListAdapter;
import com.rujian.passwordmanager.bean.PasswordBean;
import com.rujian.passwordmanager.db.dao.PwdDao;
import com.rujian.passwordmanager.util.FileUtil;
import com.rujian.passwordmanager.view.MyDialog;

import java.io.File;
import java.util.List;

import static android.os.Process.killProcess;
import static android.os.Process.myPid;

public class MainActivity extends AppCompatActivity implements NavigationView.OnNavigationItemSelectedListener {
    public static final String CHOOSE_DIR = "DIR";
    public static final String CHOOSE_FILE = "FILE";
    private static final String databaseName = "pwd.db";
    private NavigationView navigationView = null;
    private DrawerLayout drawer = null;
    private Toolbar toolbar = null;
    private ListView lv_pwd_list;
    private TextView tv_empty_pwd;
    private PwdDao pwdDao;
    private List<PasswordBean> passwordBeans;
    private EditText edt_keyword, edt_account, edt_nicname, edt_password, edt_tip;
    private Button btn_add;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);

        drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
        ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
                this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
        drawer.setDrawerListener(toggle);
        toggle.syncState();

        navigationView = (NavigationView) findViewById(R.id.nav_view);
        navigationView.setNavigationItemSelectedListener(this);

        lv_pwd_list = (ListView) findViewById(R.id.lv_pwd_list);
        tv_empty_pwd = (TextView) findViewById(R.id.tv_empty_pwd);

        pwdDao = new PwdDao(getApplicationContext());
        passwordBeans = pwdDao.getAccount("");
        if (passwordBeans.isEmpty()) {
            tv_empty_pwd.setVisibility(View.VISIBLE);
            lv_pwd_list.setVisibility(View.GONE);
        } else {
            tv_empty_pwd.setVisibility(View.GONE);
            lv_pwd_list.setVisibility(View.VISIBLE);
            lv_pwd_list.setAdapter(new PwdListAdapter(getApplicationContext(), passwordBeans));
        }
        lv_pwd_list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                Intent intent = new Intent(MainActivity.this, PwdDetailActivity.class);
                intent.putExtra("pwdDetail", passwordBeans.get(i));
                startActivity(intent);
            }
        });
    }

    public void getdata(String keyword) {
        passwordBeans = pwdDao.getAccount(keyword);
        if (!passwordBeans.isEmpty()) {
            lv_pwd_list.setAdapter(new PwdListAdapter(getApplicationContext(), passwordBeans));
            tv_empty_pwd.setVisibility(View.GONE);
            lv_pwd_list.setVisibility(View.VISIBLE);
        } else {
            tv_empty_pwd.setVisibility(View.VISIBLE);
            lv_pwd_list.setVisibility(View.GONE);
            Toast.makeText(getApplicationContext(), "找不到记录", Toast.LENGTH_SHORT).show();
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
        getdata("");
    }

    @SuppressWarnings("StatementWithEmptyBody")
    @Override
    public boolean onNavigationItemSelected(MenuItem item) {
        int id = item.getItemId();
        if (id == R.id.nav_backup_lib) {
            Intent intent = new Intent(MainActivity.this, FileChooserActivity.class);
            intent.putExtra("isChooseFile", false);
            startActivityForResult(intent, 0x122);
        } else if (id == R.id.nav_restore_lib) {
            Intent intent = new Intent(MainActivity.this, FileChooserActivity.class);
            intent.putExtra("isChooseFile", true);
            startActivityForResult(intent, 0x123);
        } else if (id == R.id.nav_delete_lib) {
            MyDialog myDialog3 = new MyDialog(MainActivity.this);
            myDialog3.showDialog("清空", "确定要清空数据记录吗？", true, new MyDialog.AfterClickBtn() {
                @Override
                public void clickOk() {
                    PwdDao pwdDao = new PwdDao(MainActivity.this);
                    pwdDao.deleteAllAccount();
                    getdata("");
                }

                @Override
                public void clickConcel() {
                }
            });
        } else if (id == R.id.nav_reset_gesture) {
            Intent intent = new Intent(MainActivity.this, ResetGestureLockActivity.class);
            startActivity(intent);
        } else if (id == R.id.nav_about) {
            StringBuffer message = new StringBuffer();
            message.append("作者：Aaron\n邮箱：103514303@qq.com\n版本：V");
            try {
                String version = getPackageManager().getPackageInfo(this.getPackageName(), 0).versionName;
                message.append(version);
            } catch (PackageManager.NameNotFoundException e) {
                e.printStackTrace();
            }
            MyDialog myDialog = new MyDialog(MainActivity.this);
            myDialog.showDialog("关于", message.toString(), false, null);
        } else if (id == R.id.nav_logout) {
            MyDialog myDialog2 = new MyDialog(MainActivity.this);
            myDialog2.showDialog("退出", "确定要退出吗？", true, new MyDialog.AfterClickBtn() {
                @Override
                public void clickOk() {
                    finish();
                    killProcess(myPid());
                }

                @Override
                public void clickConcel() {
                }
            });
        }

        drawer.closeDrawer(GravityCompat.START);
        return true;
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (requestCode == 0x122) {//备份
            if (data != null) {
                String path = data.getStringExtra(MainActivity.CHOOSE_DIR);
                FileUtil fileUtil = new FileUtil(MainActivity.this);
                if (fileUtil.backupDatabase(databaseName, path + File.separator + databaseName)) {
                    Toast.makeText(getApplicationContext(), "备份成功", Toast.LENGTH_SHORT).show();
                } else {
                    Toast.makeText(getApplicationContext(), "备份失败", Toast.LENGTH_SHORT).show();
                }
            }
        }
        if (requestCode == 0x123) {//恢复
            if (data != null) {
                String path2 = data.getStringExtra(MainActivity.CHOOSE_FILE);
                FileUtil fileUtil = new FileUtil(MainActivity.this);
                File file = new File(path2);
                if (file.exists()) {
                    if (fileUtil.restoteDatabase(databaseName, path2)) {
                        Toast.makeText(getApplicationContext(), "恢复成功", Toast.LENGTH_SHORT).show();
                        getdata("");
                    } else {
                        Toast.makeText(getApplicationContext(), "恢复失败", Toast.LENGTH_SHORT).show();
                    }
                } else {
                    Toast.makeText(getApplicationContext(), "文件不存在", Toast.LENGTH_SHORT).show();
                }
            }
        }
    }

    int pressBackNum = 0;

    @Override
    public void onBackPressed() {
        DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
        if (drawer.isDrawerOpen(GravityCompat.START)) {
            drawer.closeDrawer(GravityCompat.START);
        } else {
            pressBackNum++;
            if (1 == pressBackNum) {
                Toast.makeText(MainActivity.this, "再按一次退出", Toast.LENGTH_SHORT).show();
                new Handler().postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        //两秒后归零
                        pressBackNum = 0;
                    }
                }, 2000);
            } else if (2 == pressBackNum) {
                finish();
                killProcess(myPid());
            }
        }
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.main, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        int id = item.getItemId();
        if (id == R.id.action_search) {//查找
            //查找
            //1获取一个对话框的创建器
            AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
            //2所有builder设置一些参数
            LinearLayout linearLayout = new LinearLayout(MainActivity.this);
            linearLayout.setOrientation(LinearLayout.HORIZONTAL);
            LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
            linearLayout.setLayoutParams(layoutParams);

            final EditText editText = new EditText(MainActivity.this);
            LinearLayout.LayoutParams layoutParams2 = new LinearLayout.LayoutParams(0, ViewGroup.LayoutParams.WRAP_CONTENT);
            layoutParams2.weight = 1;
            editText.setLayoutParams(layoutParams2);

            Button btnSearch = new Button(MainActivity.this);
            LinearLayout.LayoutParams layoutParams3 = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
            btnSearch.setLayoutParams(layoutParams3);
            btnSearch.setText("搜索");
            btnSearch.setTextColor(Color.parseColor("#424242"));

            linearLayout.addView(editText);
            linearLayout.addView(btnSearch);

            builder.setCancelable(true);
            builder.setView(linearLayout);
            final AlertDialog dialog = builder.create();
            btnSearch.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    Toast.makeText(MainActivity.this, "搜索中...", Toast.LENGTH_SHORT).show();
                    String keyWork = editText.getText().toString().trim();
                    dialog.dismiss();
                    getdata(keyWork);
                }
            });
            dialog.show();
            return true;
        }
        if (id == R.id.action_add) {//添加
            //1获取一个对话框的创建器
            AlertDialog.Builder builder2 = new AlertDialog.Builder(MainActivity.this, R.style.dialog);

            LinearLayout linearLayout = (LinearLayout) LayoutInflater.from(getApplicationContext()).inflate(R.layout.pwd_add, null);
            edt_keyword = (EditText) linearLayout.findViewById(R.id.edt_keyword);
            edt_account = (EditText) linearLayout.findViewById(R.id.edt_account);
            edt_nicname = (EditText) linearLayout.findViewById(R.id.edt_nicname);
            edt_password = (EditText) linearLayout.findViewById(R.id.edt_password);
            edt_tip = (EditText) linearLayout.findViewById(R.id.edt_tip);
            btn_add = (Button) linearLayout.findViewById(R.id.btn_add);
            builder2.setView(linearLayout);
            final AlertDialog dialog2 = builder2.create();
            btn_add.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    String key = edt_keyword.getText().toString();
                    String account = edt_account.getText().toString();
                    String password = edt_password.getText().toString();
                    if (key == null || key.equals("")) {
                        Toast.makeText(getApplicationContext(), "关键字是搜索时必须的", Toast.LENGTH_SHORT).show();
                    } else if (account == null || account.equals("")) {
                        Toast.makeText(getApplicationContext(), "账号为空", Toast.LENGTH_SHORT).show();
                    } else if (password == null || password.equals("")) {
                        Toast.makeText(getApplicationContext(), "密码为空", Toast.LENGTH_SHORT).show();
                    } else {
                        PasswordBean passwordBean = new PasswordBean();
                        passwordBean.mg_keyWord = edt_keyword.getText().toString();
                        passwordBean.mg_account = edt_account.getText().toString();
                        passwordBean.mg_nicname = edt_nicname.getText().toString();
                        try {
                            passwordBean.mg_password = edt_password.getText().toString();
                            System.out.println("---------" + passwordBean.mg_password);
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                        passwordBean.mg_tip = edt_tip.getText().toString();
                        pwdDao = new PwdDao(getApplicationContext());
                        switch (pwdDao.addAccount(passwordBean)) {
                            case 0x124:
                                getdata("");
                                Toast.makeText(getApplicationContext(), "添加成功", Toast.LENGTH_SHORT).show();
                                dialog2.dismiss();
                                break;
                            case 0x125:
                                Toast.makeText(getApplicationContext(), "添加失败", Toast.LENGTH_SHORT).show();
                                break;
                            case 0x126:
                                Intent intent = new Intent(getApplicationContext(), LoginActivity.class);
                                startActivity(intent);
                                break;
                        }
                    }
                }
            });

            dialog2.show();
            return true;
        }
        return super.onOptionsItemSelected(item);
    }

}
